# coding: utf-8

import tornado
import json
import datetime
from bson import ObjectId
from handlers.base import BaseHandler

class CheckInHandler(BaseHandler):

    @tornado.gen.coroutine
    def get(self):
        try:
            rid = self.get_query_argument('rid')
            healthPlanId = self.get_query_argument('pid')
        except Exception as e:
            print(e)
            self.response_msg(400, '参数错误')
            return
        try:
            checkInList = self.db.HMRolesPlanCheck.find({'role': rid, 'plan': healthPlanId}, {'created_at': 1, '_id': 0})\
                                                 .sort('create_at', -1)
            results = []
            while(yield checkInList.fetch_next):
                checkIdObj = checkInList.next_object()
                checkIdObj['created_at_day'] = checkIdObj['created_at'].strftime('%Y-%m-%d')
                checkIdObj['created_at_time'] = checkIdObj['created_at'].strftime('%H:%I')
                del checkIdObj['created_at']
                results.append(checkIdObj)
            self.response_msg(200, '获取签到列表', results)
        except Exception as e:
            print(e)
            self.response_msg(400, '查询失败')

    @tornado.gen.coroutine
    def post(self):
        try:
            rid = self.get_argument('rid')
            healthPlanId = self.get_argument('pid')
        except Exception as e:
            print(e)
            self.response_msg(400, '输入参数错误')
        try:
            ret = yield self.db.HMRolesPlanCheck.save({'role': rid, 'plan': healthPlanId, 'created_at': datetime.datetime.now()})
            self.response_msg(200, '签到成功', {'objectId': str(ret)})
        except Exception as e:
            print(e)
            self.response_msg(400, '签到失败')